<?php
/**
 * 注册接口
 * @author Edwin
 */

namespace V1\Controller;

use Common\Controller\ApiController;
use Think\Exception;

class RegisterController extends ApiController
{

    public function _initialize()
    {
        //模块初始化，重写父类方法，避免该模块进入token验证
    }

    public function rest()
    {
        switch ($this->_method) {
            case 'post':
                $this->register();
                break;
            default:
                return;
                break;
        }
    }

    /**
     * 新用户注册
     */
    public function register()
    {
        $mobile = trim(I('post.mobile'));
        $key = md5($mobile) . 'register_code';
        try {
            $member_profile = D('Member')->getUserFromMobile($mobile);
            if ($member_profile) {
                $this->myApiPrint(C('STATUS')['202'], 201, false);
            } else {
                if (S($key) == I('post.verify_code')) {
                    $show['status'] = D('Member')->register(I('post.'));
                    if (true == $show['status']) {
                        $member_info = D('Member')->getUserFromMobile($mobile);
                        //默认添加信息到个人资料表
                        D('MemberProfile')->set_member_profile($member_info['userid']);
                        //判断邀请码是否存在
                        $code = D('MemberProfile')->check_apply_code(strtolower(I('post.apply_code')));
                        if ($code == 1) {
                            // 双方各加 100积分
                            D('MemberProfile')->add_apply_code_score($member_info['userid'], I('post.apply_code'));
                            // 邀请信息添加到邀请表
                            D('MemberCode')->addApplyCode(I('post.apply_code'), $member_info['userid']);
                        }
                        $this->myApiPrint(C('STATUS')['200'], 200, true);
                    } else {
                        $this->myApiPrint('用户添加错误', 203, false);
                    }
                } else {
                    $this->myApiPrint(C('STATUS')['223'], 202, false);
                }
            }
        } catch (Exception $exception) {
            $this->myApiPrint(C('STATUS')['101'], 400, false);
        }
    }
}
